package com.yulang.security.mobile;

import com.yulang.security.handler.CustomAuthFailureHandler;
import com.yulang.security.handler.CustomAuthSuccessHandler;
import com.yulang.security.provider.MobileAuthProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.stereotype.Component;

/**
 * 用于组合 有关手机登录的相关的组件
 */
@Component
public class MobileAuthConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {


    @Autowired
    private CustomAuthFailureHandler customAuthFailureHandler;

    @Autowired
    private CustomAuthSuccessHandler customAuthSuccessHandler;

    @Qualifier("mobileUserDetailsServiceImpl")
    @Autowired
    private UserDetailsService mobileUserDetailsServiceImpl;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        MobileAuthFilter mobileAuthFilter = new MobileAuthFilter();
        mobileAuthFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        mobileAuthFilter.setAuthenticationSuccessHandler(customAuthSuccessHandler);
        mobileAuthFilter.setAuthenticationFailureHandler(customAuthFailureHandler);
        mobileAuthFilter.setSessionAuthenticationStrategy(http.getSharedObject(SessionAuthenticationStrategy.class)); // 限制登录用户数的配置
        // 记住我功能需要传递一个对象
        mobileAuthFilter.setRememberMeServices(http.getSharedObject(RememberMeServices.class));

        MobileAuthProvider mobileAuthProvider = new MobileAuthProvider();
        mobileAuthProvider.setUserDetailsService(mobileUserDetailsServiceImpl);
        http.authenticationProvider(mobileAuthProvider).addFilterAfter(mobileAuthFilter,UsernamePasswordAuthenticationFilter.class);
    }
}
